﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.Data;
using Sunlight.Dispatch.Model;
using Sunlight.Dispatch.Tools;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Extensions;

namespace Sunlight.Dispatch.UI {
    //https://www.cnblogs.com/luxiaoxun/p/3784729.html
    public partial class InitFrm : BaseFrm {
        public InitFrm() {
            InitializeComponent();
            this.Load += InitFrm_Load;
        }

        private void InitFrm_Load(object sender, EventArgs e) {
            var systemPath = Environment.GetEnvironmentVariable("ProgramFiles");
            var defaultPath = string.IsNullOrEmpty(systemPath) ? "c:/" : systemPath;
            this.txbEnvironmentPath.Text = Path.Combine(defaultPath, "SQLite\\init.sqlite");
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.SelectionChanged += this.DataGridView_SelectionChanged;
            this.dataGridView1.RowPostPaint += this.DataGridView_RowPostPaint;
        }

        private void btnExecute_Click(object sender, EventArgs e) {
            if(radioButtonDefault.Checked) {
                if(!Directory.Exists(Path.GetDirectoryName(this.txbEnvironmentPath.Text)))
                    // ReSharper disable once AssignNullToNotNullAttribute
                    Directory.CreateDirectory(Path.GetDirectoryName(this.txbEnvironmentPath.Text));
                if(File.Exists(this.txbEnvironmentPath.Text)) {
                    this.lblResultFirst.Text = "";
                    var result = MessageBoxEx.Show(this, "文件已经存在，是否继续执行?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                    if(result != DialogResult.OK) {
                        return;
                    }
                }
                var conn = new SQLiteConnection();
                conn.CreateDataBaseAndInit(this.txbEnvironmentPath.Text, (int)SQLiteStoryPathTypeEnum.默认);

                if(File.Exists(this.txbEnvironmentPath.Text)) {
                    this.lblResultFirst.Text = "执行成功";
                } else {
                    MessageBoxEx.Show(this, "执行失败，请检查", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void tsbSave_Click(object sender, EventArgs e) {
            if(string.IsNullOrEmpty(this.txbDataBaseName.Text)) {
                MessageBoxEx.Show(this, "数据库名称不允许为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if(string.IsNullOrEmpty(this.txbConnectString.Text)) {
                MessageBoxEx.Show(this, "连接字符串不允许为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var msg = string.Empty;
            if(!Utils.IsCanConnect(out msg, this.txbConnectString.Text)) {
                MessageBoxEx.Show(this, "此连接不通，请检查是否输入有误,\r\n或是否能正常访问该数据库服务器", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var config = Utils.DeSerialize();
            if(config == null) {
                MessageBoxEx.Show(this, "请先初始化项目配置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            using(var conn = new SQLiteConnection(string.Format($"Data Source={config.SqliteStoryPath};Version=3;"))) {
                conn.Open();
                //创建连接字符串存储表
                string sql = $"insert into ConnectStringConfigTb (Id, Name, ConnectString) values ('{Utils.NewGuid()}','{this.txbDataBaseName.Text}','{this.txbConnectString.Text}')";
                var command = new SQLiteCommand(sql, conn);
                command.ExecuteNonQuery();

                var sqlExecute = "select Id,Name,ConnectString from ConnectStringConfigTb";
                command = new SQLiteCommand(sqlExecute, conn);
                var reader = command.ExecuteReader();
                var source = new List<ConnectStringConfigTb>();
                while(reader.Read()) {
                    source.Add(new ConnectStringConfigTb {
                        Id = reader[0].ToString(),
                        Name = reader[1].ToString(),
                        ConnectString = reader[2].ToString()
                    });
                }
                this.dataGridView1.ClearDataSource();
                this.dataGridView1.DataSource = source;
            }
        }

        private void tsbSearch_Click(object sender, EventArgs e) {
            var config = Utils.DeSerialize();
            if(config == null)
                return;
            using(var conn = new SQLiteConnection(string.Format($"Data Source={config.SqliteStoryPath};Version=3;"))) {
                conn.Open();
                var sqlExecute = "select Id,Name,ConnectString from ConnectStringConfigTb";
                var command = new SQLiteCommand(sqlExecute, conn);
                var reader = command.ExecuteReader();
                var source = new List<ConnectStringConfigTb>();
                while(reader.Read()) {
                    source.Add(new ConnectStringConfigTb {
                        Id = reader[0].ToString(),
                        Name = reader[1].ToString(),
                        ConnectString = reader[2].ToString()
                    });
                }
                this.dataGridView1.ClearDataSource();
                this.dataGridView1.DataSource = source;
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e) {
            var config = Utils.DeSerialize();
            if(this.dataGridView1.Rows.Count <= 0 || config == null)
                return;
            var rows = this.dataGridView1.Rows.Cast<DataGridViewRow>().Select(d => (ConnectStringConfigTb)d.DataBoundItem).ToList();
            if(rows.All(d => !d.IsSelected)) {
                MessageBoxEx.Show(this, "请选择要删除的数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if(rows.Count(d => d.IsSelected) > 1) {
                MessageBoxEx.Show(this, "只能单条进行删除，请重新选择", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var item = rows.First(d => d.IsSelected);
            if(item == null)
                return;
            using(var conn = new SQLiteConnection(string.Format($"Data Source={config.SqliteStoryPath};Version=3;"))) {
                conn.Open();
                var sqlDelete = $"delete from ConnectStringConfigTb where Id = '{item.Id}'";
                var command = new SQLiteCommand(sqlDelete, conn);
                command.ExecuteNonQuery();
                var sqlExecute = "select Id,Name,ConnectString from ConnectStringConfigTb";
                command = new SQLiteCommand(sqlExecute, conn);
                var reader = command.ExecuteReader();
                var source = new List<ConnectStringConfigTb>();
                while(reader.Read()) {
                    source.Add(new ConnectStringConfigTb {
                        Id = reader[0].ToString(),
                        Name = reader[1].ToString(),
                        ConnectString = reader[2].ToString()
                    });
                }
                this.dataGridView1.ClearDataSource();
                this.dataGridView1.DataSource = source;
            }
        }
    }
}

